<template>
  <div class="admin-data">
    <el-row class="mb-20">
      <el-col :span="21">
        <el-card>
          <div style="display: flex; align-items: center; margin-bottom: 10px;">
            <el-button type="primary" icon="el-icon-upload" @click="handleBackup" :loading="isBackupLoading">一键备份</el-button>
          </div>
          <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <el-table :data="backupList" style="table">
              <el-table-column
                v-for="col in backupColumns"
                :key="col.prop"
                :prop="col.prop"
                :label="col.label"
                width="320"
                align="center"
              />
              <el-table-column label="操作" width="250" align="center">
                <template slot-scope="{ row }">
                  <div style="display: flex; justify-content: space-between;">
                    <el-button type="primary" size="mini" @click="restoreToDate(row)" :loading="isRestoring" style="margin-right: 5px;">还原</el-button>
                    <el-button type="primary" size="mini" @click="exportData(row)" :loading="isExporting">导出</el-button>
                    <el-button type="danger" size="mini" @click="confirmDelete(row)" :loading="isDeleteData">删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref } from 'vue';
import axios from 'axios';
import baseUrl from '../assets/path.js';
import { MessageBox, Message } from 'element-ui';

export default {
  name: 'AdminData',
  data() {
    return {
      activeTab: 'backup',
      baseUrl,
      backupList: [],
      isBackupLoading: false,
      isRestoring: false,
      isDeleteData: false,
      isExporting: false,
      backupColumns: [
        { prop: 'backup_date', label: '备份日期' },
      ],
    };
  },
  mounted() {
    this.getDataBackups();
  },
  methods: {
    async getDataBackups() {
      try {
        const res = await axios.get(`${this.baseUrl}/admin/getDataBackups`);
        this.backupList = res.data;
      } catch (error) {
        console.error(error);
      }
    },
    handleBackup() {
      this.isBackupLoading = true;
      axios.post(`${this.baseUrl}/admin/createBackup`)
        .then(response => {
          if (response.status === 200) {
            Message.success('备份成功');
            this.getDataBackups();
          } else {
            Message.error('备份失败，请重试');
          }
        })
        .catch(error => {
          console.error('备份错误:', error);
          Message.error('备份失败，请重试');
        })
        .finally(() => {
          this.isBackupLoading = false;
        });
    },
    restoreToDate(row) {
      this.isRestoring = true; // 设置加载状态
	  
      const url = `${this.baseUrl}/admin/restoreDataBackup/${row.backup_id}`;
    
      axios({
        url: url,
        method: 'POST', // 通常还原操作使用 POST 方法
      })
      .then((response) => {
        if (response.status === 200) {
          Message.success('还原成功');
          this.getDataBackups(); // 重新获取备份列表以更新界面
        } else {
          Message.error('还原失败，请重试');
        }
      })
      .catch((error) => {
        console.error('还原错误:', error);
        Message.error('还原失败，请重试');
      })
      .finally(() => {
        this.isRestoring = false; // 重置加载状态
      });
    },
    exportData(row) {
      this.isExporting = true; // 设置加载状态
      const sampleFileUrl = `${this.baseUrl}/static/backs/`+row.backup_id;
      window.open(sampleFileUrl);
	  this.isExporting = false; // 设置加载状态
    },


    handleTabClick(tab) {
      // 处理标签点击的逻辑
    },
    confirmDelete(row) {
      MessageBox.confirm('您确定要删除这个备份吗?', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        this.deleteData(row);
      })
      .catch(() => {
        console.log('删除操作被取消');
      });
    },
    async deleteData(row) {
      this.isDeleteData = true;
      try {
        const res = await axios.delete(`${this.baseUrl}/admin/deleteDataBackup/${row.backup_id}`);
        if (res.status === 200) {
          this.backupList = this.backupList.filter(item => item.backup_id !== row.backup_id);
          Message.success('备份已删除');
        } else {
          Message.error('删除备份失败');
        }
      } catch (error) {
        console.error('Error deleting backup:', error);
        Message.error('删除备份失败');
      } finally {
        this.isDeleteData = false;
      }
    },
  }
};
</script>

<style scoped>
.admin-data {
  padding: 5px;
  margin-left: 150px;
}

.el-card {
  margin-bottom: 20px;
  height:800px;
  overflow:auto;
}

.el-table {
  width: 100%;
  overflow: auto;
  text-align: center;
  margin-left: 230px;
}

.el-button {
  margin: 10px 0;
}

.el-date-picker {
  width: 100%;
}

.table {
  margin-top: 20px;
}

.el-tabs__header {
  padding: 0;
}
</style>